// import Vue from "vue";
import axios from "axios";
import {
  addPendingRequest,
  removePendingRequest,
  requestAgainSend,
} from "./auxiliary";

// const CANCEL_TOKEN = axios.CancelToken;
// Vue.prototype.$httpRequestList = [];

const instance = axios.create({
  timeout: 15000,
  baseURL: "http://127.0.0.1:7001",
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    removePendingRequest(config);
    addPendingRequest(config);
    // console.log(config);
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    removePendingRequest(response.config);
    return response;
  },
  (error) => {
    // 对响应错误做点什么
    requestAgainSend(error, instance);

    removePendingRequest(error.config); // cancleToken 中断请求
    if (Object.keys(error)[0] === "message") {
      console.log("原来同一请求已被中断");
      return;
    }
    return Promise.reject(error);
  }
);

export const api = async (url, method = "get", targrt) => {
  const info = await instance({
    url,
    method,
    ...targrt,
  });
  return info;
};
